package com.sen.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sen.dao.MenuRoleDao;
import com.sen.dao.RoleDao;
import com.sen.entity.MenuEntity;
import com.sen.entity.MenuRoleEntity;
import com.sen.entity.RoleEntity;
import com.sen.service.MenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Service("menuRoleService")
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleDao, MenuRoleEntity> implements MenuRoleService {

    @Autowired
    MenuRoleDao menuRoleDao;
    @Autowired
    RoleDao roleDao;

    /**
     * 通过id删除和修改使用
     * @param id 角色的id
     * @param menuList 用户选中的权限列表
     */
    @Override
    @Transactional
    public void addRoleMenu(String id, String menuList) {
        try {
            //通过id删除用户原本权限
            menuRoleDao.delete(new UpdateWrapper<MenuRoleEntity>().eq("roleid", id));
            List<MenuEntity> menuEntityList = JSON.parseArray(menuList, MenuEntity.class);
            Set<Integer> pids = new LinkedHashSet<>();
            List<Integer> ids = new ArrayList<>();
            for (MenuEntity menuEntity : menuEntityList) {
                if (menuEntity.getType()!=1){
                    ids.add(menuEntity.getId());
                }
                if (menuEntity.getPid()!=0){
                    pids.add(menuEntity.getPid());
                }
            }
            for (Integer integer : ids) {
                menuRoleDao.addRoleMenu(id, integer);
            }
            for (Integer pid : pids) {
                menuRoleDao.addRoleMenu(id, pid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加新角色
     * @param rolename
     * @param remark
     * @param menuList
     */
    @Override
    @Transactional
    public void addRoleMenu(String rolename, String remark, String menuList) {
        RoleEntity role = new RoleEntity();
        role.setRolename(rolename);
        role.setRemark(remark);
        //添加新角色
        roleDao.addRole(role);
        System.out.println(role);
        String id = String.valueOf(role.getId());
        List<MenuEntity> menuEntityList = JSON.parseArray(menuList, MenuEntity.class);
        //添加新的角色权限
        for (MenuEntity menuEntity : menuEntityList) {
            menuRoleDao.addRoleMenu(id, menuEntity.getId());
        }
    }
}
